﻿namespace MD5
{
    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

    public class MD5Util
    {
        public static string GetFileMD5(string fileName)
        {
            string str = string.Empty;
            if (!File.Exists(fileName))
            {
                return str;
            }
            using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                return GetMD5Hash(stream);
            }
        }

        public static string GetMD5Hash(Stream stream)
        {
            byte[] buffer = MD5.Create().ComputeHash(stream);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < buffer.Length; i++)
            {
                builder.Append(buffer[i].ToString("x2"));
            }
            return builder.ToString();
        }

        public static string GetMD5Hash(string input)
        {
            byte[] buffer = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(input));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < buffer.Length; i++)
            {
                builder.Append(buffer[i].ToString("x2"));
            }
            return builder.ToString();
        }

        public static bool VerfyMd5Hash(string input, string hash)
        {
            string x = GetMD5Hash(input);
            StringComparer ordinalIgnoreCase = StringComparer.OrdinalIgnoreCase;
            return (0 == ordinalIgnoreCase.Compare(x, hash));
        }
    }
}

